import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

  const routes = [
  {
    path: '/login',
    name: 'LoginPages',
    component: () => import('@/views/login/Login.vue'),
    meta: {
      title: 'login'
    }
  },
  {
    path: '/register',
    name: 'RegisterPages',
    component: () => import('@/views/register/Register.vue'),
    meta: {
      title: 'registers'
    }
  },
  {
    path: '/settings',
    name: 'SettingsPages',
    component: () => import('@/views/settings/Settings.vue'),
    meta: {
      requireAuth: true,
      title: 'settings'
    }
  },
  {
    path: '/article/:aid',
    name: 'ArticlePages',
    component: () => import('@/views/article/Article.vue'),
    meta: {
      requireAuth: true,
      title: 'article'
    }
  },
  {
    path: '/editor',
    component: () => import('@/views/editor/CreateArticle.vue'),
    meta: {
      requireAuth: true,
      title: 'editor'
    }
  },
  {
    path: '/editor/:slug',
    component: () => import('@/views/editor/EditArticle.vue'),
    meta: {
      requireAuth: true
    }
  },
  {
    path: '/profile/:uid',
    name: 'ProfilePages',
    component: () => import('@/views/profile/Profile.vue'),
    meta: {
      requireAuth: true,
    },
    children:[
      {
        path: '/profile/:uid/myarticles',
        name: 'MyArticlesPages',
        component: () => import('@/views/profile/MyArticles.vue'),
        meta: {
          requireAuth: true,
          title: 'myarticles'
        }
      },
      {
        path: '/profile/:uid/favarticles',
        name: 'FavArticlesPages',
        component: () => import('@/views/profile/FavArticles.vue'),
        meta: {
          requireAuth: true,
          title: 'favarticles'
        }
      },
      {
        path:'/profile/:uid',
        redirect: '/profile/:uid/myarticles'
      }
    ]
  },
  {
    path: '/',
    name: 'HomePages',
    component: () => import('@/views/home/Home.vue'),
    meta:{
      title: 'home'
    }
  },
  { // 配置404组件, 放在最后
    path: '/*',
    component: () => import('@/views/notFound/index.vue')
  },
]

const router = new VueRouter({
  // mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next)  => {
  if(from.name == "login"){ // 如果不需要权限校验，直接进入路由界面
    next();
  }else if(to.meta.requireAuth){
    // 判断该路由是否需要登录权限
    if (sessionStorage.getItem("token_key")) {  // 获取当前的token是否存在
      next();
    } else {
      next({
        path: '/login', // 将跳转的路由path作为参数，登录成功后跳转到该路由
        query: {redirect: to.fullPath}
      })
    }
  }else { // 如果不需要权限校验，直接进入路由界面
    next();
  }

  if(to.meta.title){
    document.title = to.meta.title
  }
});

export default router
